/**
 * Created by vimer on 15/8/25.
 */

var updateSerialList = function(){
    // 初始化串口列表
    Serial.getList(function(arr){
        Ui.initSerial(arr );
    });
}

var tryOpenDevice = function(spName,flag){
    var reconnectDevice = function () {
        Log.log("等待插入设备") ;
        Ui.updatePlugStatus(false);
        Ui.updateMainLog(true,"等待插入设备");
        var TaskList = getTaskList();
        Ui.initTask(TaskList);
        setTimeout(function(){
            tryOpenDevice(spName ,false );

        }, 3000);
    };
    Serial.open(spName, reconnectDevice ,function(sp){
        if(!sp){
            if(flag){
                Log.log("无法打开设备:" + spName);
            }
            reconnectDevice();
            return;
        }
        Ui.updatePlugStatus(true);
        Log.log("成功连接到设备");
        Ui.updateMainLog("开始测试");
        Log.log("正在测试");
        newAutoTest(sp);
    });
};

var newAutoTest =  function(sp ){
    var TaskList = getTaskList();
    var  taskMaxIndex = TaskList.length;
    var taskIndex = 0;
    var async = require('async');
    Ui.initTask(TaskList);
    var q = async.queue(function(task,callback){
        Log.log("开始任务：" + task.name);
        if(task.startCommand){
            var command =  task.startCommand();
            Log.log("执行命令：" + command);
        }

        Ui.updateMainLog("正在测试:" + task.name);
        Ui.updateTaskStatus(task.id,TaskStatus.RUNNING);
        var count = 0;
        count = task.repeat || 1;
        if( count !== 1){
            Ui.updateTaskRate(task.id, 0);
        }

        async.whilst (
            function () { return count > 0; },
            function(next) {
                if( !command){
                        task.do(
                            function(message){
                                Log.serialLog(message);
                            },
                            function(err){
                                if(err){
                                    Ui.updateMainLog(true, "测试失败：" + task.name + ":" + err);
                                    next(err);
                                    return;
                                }
                                else {
                                    next();
                                }
                            }
                        );
                }
                else {
                    sp.write(command, function (err) {
                        if (err) {
                            Log.log(err);
                            next(err);
                        }
                    });
                    sp.on('data', function (data) {
                        Log.serialLog(data.toString());
                        task.status(data.toString(), function (status) {
                            if (status != TaskStatus.RUNNING) {
                                sp.removeAllListeners();
                                if (status == TaskStatus.FAIL ) {
                                    Ui.updateMainLog(true, "测试失败：" + task.name);
                                    next("err");
                                }
                                else {
                                    count--;
                                    if( task.repeat !== 1){
                                        Ui.updateTaskRate(task.id, (task.repeat - count) / task.repeat * 100);
                                    }
                                    next();
                                }
                            }
                        });
                    });

                }
            },
            function(err){
                if(!err){
                    if( task.endCommand){
                        sp.write(task.endCommand(), function (err) { });
                    }
                    Ui.updateTaskStatus(task.id, TaskStatus.GOOD);
                }
                else {
                    Ui.updateTaskStatus(task.id, TaskStatus.FAIL);
                }
                callback(err) ;
            }
        );
    },1);
    q.drain = function() {
        Ui.updateMainLog("完成测试");
        Log.log("完成测试");
    }

    var time =  3;
    var enableTaskList = [];
    for( var t in TaskList){
        console.log(TaskList[t]);
        if(TaskList[t].enable){
            enableTaskList.push(TaskList[t]);
        }
    }
    var downCountInterval = setInterval(function(){
        Ui.updateMainLog(time + "秒后开始测试") ;
        Log.log(time + "秒后开始测试") ;
        Ui.flashMainLog(false);
        time--;
        if(time < 0){
            clearInterval(downCountInterval);
            Ui.flashMainLog(true);
            Ui.updateMainLog("开始测试");
            q.push(enableTaskList);
        }
    },1000);


};


$(document).ready(function(){
    Ui.initLog();
    Log.setLogger(Ui.appendLog);

    var TaskList = getTaskList();
    Ui.initTask(TaskList);
    updateSerialList();
    //

    var firstTimeLogin = true;
    var _serialPort ;
    var interval = setInterval(function(){
        _serialPort = KeyValue.get("serialPort");
        if(_serialPort){
            Log.log("从存储中得到串口配置 :" + _serialPort);
            clearInterval(interval);
            Ui.updateMainLog("等待插入新的设备");
            Log.log("等待插入新的设备");
            Ui.flashMainLog(true);
            tryOpenDevice(_serialPort,true);
        }
        else if(firstTimeLogin){
            Ui.updateMainLog("请点击右上角图标选择设备");
            Log.log("请点击右上角图标选择设备");
            $("#modal1").openModal();
            firstTimeLogin = false;
        }

    },2000);

});

